package com.bw.coupon.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bw.common.core.utils.StringUtils;
import com.bw.common.redis.service.RedisService;
import com.bw.common.security.service.TokenService;
import com.bw.coupon.domain.Order;
import com.bw.coupon.domain.OrderSku;
import com.bw.coupon.domain.PaymentFlow;
import com.bw.coupon.mapper.OrderMapper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.bw.coupon.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author：尚志豪
 * @Package：com.bw.coupon.service.impl
 * @Project：doudi-group-practical_training-02
 * @name：OrderServiceImpl
 * @Date：2025/1/23 16:44
 * 异步下单：
 * 校验通过mq异步下单
 * 线程池，异步编排处理下单
 * 前台轮询查询下单结果
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private StringRedisTemplate restTemplate; // 用于前台轮询查询

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisService redisService;
    @Autowired
    private TokenService tokenService;


    @Override
    public void save(PaymentFlow paymentFlow) {

    }

    @Override
    // 前台查询订单状态（模拟数据库查询）
    public Integer checkOrderStatus(Long orderNumber) {

        // 查看是否超时
        if (!redisService.hasKey("placeOrder:" + orderNumber)){
            throw new RuntimeException("下单超时");
        }

        Object cacheObject = redisService.getCacheObject("placeOrder:" + orderNumber);

        //修改订单状态
        orderMapper.updateOrderStatus(orderNumber,(Integer) cacheObject);

        return (Integer) cacheObject;

    }

    //订单中
    private static final Integer CRD = 1;
    /**
     * 添加订单
      * @param order
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addOrder(Order order) {



        //添加订单数据
        Order orders = new Order();

        orders.setOrderNumber(order.getOrderNumber());

        orders.setOrderState(1);

        orders.setOrderMoney(order.getOrderMoney());

        orders.setUserId(1L);

        //添加订单
        orderMapper.addOrder(orders);

        //添加中间表数据
        order.getSkuIds().forEach(skuId -> {

            OrderSku orderSku = new OrderSku();

            orderSku.setSkuId(skuId);

            orderSku.setOrderId(orders.getId());

            orderMapper.addOrderSku(orderSku);

        });

    }

    /**
     * 下单
     * @param order
     */
    @Override
    public void PlaceOrder(Order order) {
        if (StringUtils.isEmpty(order.getSkuIds())){
            throw new RuntimeException("请选择结算商品");
        }
        redisService.setCacheObject("placeOrder:"+order.getOrderNumber(),CRD,60L, TimeUnit.MINUTES);

        String jsonOrder = JSONObject.toJSONString(order);

        rabbitTemplate.convertAndSend("placeOrder",jsonOrder);
    }

    /**
     * 修改订单支付状态
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateOrderPay(long outTradeNo) {
        // 根据订单号查询订单
        Order order = orderMapper.selectOrderByOrderNumber(outTradeNo);

        orderMapper.updateOrderPay(order.getId());

    }
    /**
     * 同步库存数量
     * @param skuId
     * @param inventory
     */
    @Override
    public void updateInventory(Integer skuId, Integer inventory) {
        orderMapper.updateInventory(skuId,inventory);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Long> selectOrderNumberBySkuId(long outTradeNo) {
        // 根据订单号查询订单
        Order order = orderMapper.selectOrderByOrderNumber(outTradeNo);
        // 判断订单是否存在
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        //根据订单Id查询商品Id
        List<OrderSku> orderSkus = orderMapper.selectOrderIdBySkuId(order.getId());

        // 遍历集合，获取商品Id
        List<Long> skuIds = new ArrayList<>();
        orderSkus.forEach(orderSku -> {
            skuIds.add(orderSku.getSkuId());
        });

        return skuIds;
    }

    @Override
    public void deleteCart(List<Long> skuIds) {
        skuIds.forEach(skuId -> {
            redisService.deleteObject("cart:"+skuId);
        });
    }


}
